package com.SmartCampus.system.controller;

import com.SmartCampus.system.annotation.AuthCheck;
import com.SmartCampus.system.common.BaseResponse;
import com.SmartCampus.system.common.DeleteRequest;
import com.SmartCampus.system.common.ErrorCode;
import com.SmartCampus.system.common.ResultUtils;
import com.SmartCampus.system.constant.UserConstant;
import com.SmartCampus.system.exception.BusinessException;
import com.SmartCampus.system.exception.ThrowUtils;
import com.SmartCampus.system.model.dto.course.CourseAddRequest;
import com.SmartCampus.system.model.dto.course.CourseQueryRequest;
import com.SmartCampus.system.model.dto.course.CourseUpdateRequest;
import com.SmartCampus.system.model.entity.Clazz;
import com.SmartCampus.system.model.entity.Course;
import com.SmartCampus.system.model.entity.Subjectcategory;
import com.SmartCampus.system.model.entity.User;
import com.SmartCampus.system.model.vo.CourseVO;
import com.SmartCampus.system.service.ClazzService;
import com.SmartCampus.system.service.CourseService;
import com.SmartCampus.system.service.SubjectcategoryService;
import com.SmartCampus.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 课程表接口
 *
 * @author wangliang
 */
@RestController
@RequestMapping("/course")
@Slf4j
@Api(tags = "课程表接口")
public class CourseController {

    @Resource
    private CourseService courseService;

    @Resource
    private SubjectcategoryService subjectcategoryService;

    @Resource
    private UserService userService;

    @Resource
    private ClazzService clazzService;

    // region 增删改查

    /**
     * 创建课程（仅管理员）
     *
     * @param courseAddRequest
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "创建课程（仅管理员）")
    public BaseResponse<Long> addClazz(@RequestBody CourseAddRequest courseAddRequest) {
        if (courseAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Subjectcategory> querySubject = new QueryWrapper<>();
        querySubject.eq("subjectName", courseAddRequest.getCourseName());
        if (subjectcategoryService.count(querySubject) == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "课程不存在");
        }
        Subjectcategory subjectcategory = subjectcategoryService.getOne(querySubject);
        QueryWrapper<User> queryUser = new QueryWrapper<>();
        queryUser.eq("username", courseAddRequest.getTeacherName());
        if (userService.count(queryUser) == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "教师不存在");
        }
        User user = userService.getOne(queryUser);
        Course course = new Course();
        BeanUtils.copyProperties(courseAddRequest, course);
        course.setCourseId(subjectcategory.getSubjectId());
        course.setTeacherId(user.getId());
        boolean result = courseService.save(course);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(course.getId());
    }

    /**
     * 删除课程（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除课程（仅管理员）")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能为空");
        }
        boolean result = courseService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 更新课程（仅管理员）
     *
     * @param courseUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新课程（仅管理员）")
    public BaseResponse<Boolean> updateUser(@RequestBody CourseUpdateRequest courseUpdateRequest) {
        if (courseUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }
        Course course = new Course();
        QueryWrapper<Course> queryCourse = new QueryWrapper<>();
        queryCourse.eq("id", courseUpdateRequest.getId());
        if (courseService.count(queryCourse) == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "课程不存在");
        }
        course = courseService.getOne(queryCourse);
        if (courseUpdateRequest.getCourseName() != null && !courseUpdateRequest.getCourseName().equals("")) {
            QueryWrapper<Subjectcategory> querySubject = new QueryWrapper<>();
            querySubject.eq("subjectName", courseUpdateRequest.getCourseName());
            course.setCourseId(subjectcategoryService.getOne(querySubject).getSubjectId());
        } else {
            course.setCourseId(course.getCourseId());
        }
        if (courseUpdateRequest.getTeacherName() != null && !courseUpdateRequest.getTeacherName().equals("")) {
            QueryWrapper<User> queryUser = new QueryWrapper<>();
            queryUser.eq("username", courseUpdateRequest.getTeacherName());
            course.setTeacherId(userService.getOne(queryUser).getId());
        } else {
            course.setTeacherId(course.getTeacherId());
        }
        if (courseUpdateRequest.getClazzName() == null || courseUpdateRequest.getClazzName().equals("")) {
            courseUpdateRequest.setClazzName(course.getClazzName());
        } else {
            course.setClazzName(course.getClazzName());
        }
        if (courseUpdateRequest == null || courseUpdateRequest.getCredit().equals("")) {
            courseUpdateRequest.setCredit(course.getCredit());
        }

        BeanUtils.copyProperties(courseUpdateRequest, course);
        boolean result = courseService.updateById(course);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 获取全部班级课程列表（仅管理员）
     *
     * @param courseQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "获取全部班级课程列表（仅管理员）")
    public BaseResponse<Page<CourseVO>> listClazzByPage(@RequestBody CourseQueryRequest courseQueryRequest) {
        long current = courseQueryRequest.getCurrent() == 0 ? 1 : courseQueryRequest.getCurrent();
        long size = courseQueryRequest.getPageSize() == 0 ? 10 : courseQueryRequest.getPageSize();
        Page<CourseVO> page = new Page<>(current, size);
        Page<CourseVO> courseVOPage = courseService.getAll(page, courseQueryRequest);
        if (courseVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(courseVOPage);
    }

    /**
     * 获取学生的班级课程列表（仅学生）
     *
     * @param courseQueryRequest
     * @return
     */
    @PostMapping("/get/all/student")
    @ApiOperation(value = "获取学生的班级课程列表（仅学生）")
    public BaseResponse<Page<CourseVO>> listClazzByStudent(@RequestBody CourseQueryRequest courseQueryRequest, HttpServletRequest request) {
        long current = courseQueryRequest.getCurrent() == 0 ? 1 : courseQueryRequest.getCurrent();
        long size = courseQueryRequest.getPageSize() == 0 ? 10 : courseQueryRequest.getPageSize();
        Long clazzId = userService.getLoginUser(request).getClazzId();
        QueryWrapper<Clazz> queryCourse = new QueryWrapper<>();
        queryCourse.eq("id", clazzId);
        if (clazzService.count(queryCourse) == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "班级不存在");
        }
        String clazzName = clazzService.getOne(queryCourse).getName();
        Page<CourseVO> page = new Page<>(current, size);
        Page<CourseVO> courseVOPage = courseService.getStudent(page, courseQueryRequest, clazzName);
        if (courseVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(courseVOPage);
    }

    /**
     * 获取老师的班级课程列表（仅老师）
     *
     * @param courseQueryRequest
     * @return
     */
    @PostMapping("/get/all/teacher")
    @ApiOperation(value = "获取老师的班级课程列表（仅老师）")
    public BaseResponse<Page<CourseVO>> listClazzByTeacher(@RequestBody CourseQueryRequest courseQueryRequest, HttpServletRequest request) {
        long current = courseQueryRequest.getCurrent() == 0 ? 1 : courseQueryRequest.getCurrent();
        long size = courseQueryRequest.getPageSize() == 0 ? 10 : courseQueryRequest.getPageSize();
        Long teacherId = userService.getLoginUser(request).getId();
        Page<CourseVO> page = new Page<>(current, size);
        Page<CourseVO> courseVOPage = courseService.getTeacher(page, courseQueryRequest, teacherId);
        if (courseVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(courseVOPage);
    }

    // endregion
}
